package com.autonavi.yunda.yunji.controller;

import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import com.autonavi.yunda.yunji.controller.request.DynamicConfigRequest;
import com.autonavi.yunda.yunji.core.enums.OperationRecordType;
import com.autonavi.yunda.yunji.core.model.condition.DynamicConfigQueryCondition;
import com.autonavi.yunda.yunji.core.model.dto.DynamicConfigDTO;
import com.autonavi.yunda.yunji.core.service.DynamicConfigService;
import com.autonavi.yunda.yunji.core.vo.response.DynamicConfigPageVO;
import com.autonavi.yunda.yunji.service.OperationRecordService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.logging.log4j.util.Strings;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cizhong.wcs
 * @date 2022/3/7 7:33 下午
 */
@RestController
@RequestMapping("/dynamicConfig")
public class DynamicConfigController {

    @Resource
    private DynamicConfigService dynamicConfigService;
    @Resource
    private OperationRecordService operationRecordService;


    @PostMapping("add")
    public Long add(@Validated @RequestBody DynamicConfigRequest request) {
        Long id = dynamicConfigService.add(request.toAddDTO());
        operationRecordService.add( OperationRecordType.DynamicSubType.CREATE, id.toString());
        return id;
    }

    @PostMapping("update")
    public String update(@Validated @RequestBody DynamicConfigRequest request) {
        UpdateWrapper<DynamicConfigDTO> updateWrapper = request.toUpdateWrapper();
        dynamicConfigService.findByIdOrThrow(request.getId());
        dynamicConfigService.update(updateWrapper);
        operationRecordService.add( OperationRecordType.DynamicSubType.UPDATE, request.getId().toString());
        return "success";
    }

    @PostMapping("list")
    public DynamicConfigPageVO list(@Validated @RequestBody DynamicConfigQueryCondition request) {
        return dynamicConfigService.listPage(request);
    }

    @GetMapping("listAllKeys")
    public List<String> listAllKeys(@RequestParam String projectId) {
        AmapPreconditions.checkArgumentForUser(Strings.isNotBlank(projectId), "projectId 不能为空");
        return dynamicConfigService.listAll(DynamicConfigQueryCondition.builder().projectId(projectId).build())
                .stream().map(DynamicConfigDTO::getKeyName)
                .collect(Collectors.toList());
    }

}
